/*登录组件*/
import React, {useEffect, useState} from "react";
import {
    Button,
    Checkbox,
    CircularProgress,
    Input,
    Spacer,
    Tab,
    Tabs
} from "@nextui-org/react";
import axios from "axios";
import ToastUtil from "@/app/utils/toastUtil";
import cookie from 'react-cookies'
import {useRouter} from "next/navigation";
import {encodeToBase64} from "next/dist/build/webpack/loaders/utils";
import {validateParameter} from "@/app/utils/validation";
import LoginService, {MobileLoginService, SendVerificationCode} from "@/app/service/loginService";
import PubSub from 'pubsub-js';

/**
 * 账号密码登录表单
 * @param loading
 * @param setLoading
 * @constructor
 */
function PasswordLoginForm({loading, setLoading}: any) {
    /*账号密码数据和状态*/
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    /*定义显示隐藏按钮状态*/
    const [isVisible, setIsVisible] = React.useState(false);
    /*更新状态*/
    const toggleVisibility = () => setIsVisible(!isVisible);

    /*获取消息（username | password）*/
    PubSub.unsubscribe('username')/*解触*/
    PubSub.subscribe('username', (_, data) => {
        setUsername(data)
        /*/接受完取消订阅*/
        PubSub.unsubscribe('username')
    })
    PubSub.unsubscribe('password')/*解触*/
    PubSub.subscribe('password', (_, data) => {
        setPassword(data)
        /*/接受完取消订阅*/
        PubSub.unsubscribe('password')
    })

    return (
        <>
            <Input
                isClearable
                className={`dark:text-white`}
                id={'username'}
                name={'username'}
                type={"text"}
                label={"用户名"}
                variant={"faded"}
                placeholder={"请输出您的用户名"}
                onClear={() => console.log("cleared")}
                isRequired={true}
                value={username}
                onChange={({target: {value}}) => setUsername(value)}
            />
            <Spacer y={1.5}/>
            <Input
                name={'password'}
                className={`dark:text-white`}
                id={'password'}
                isClearable={false}
                label={"密码"}
                variant={"faded"}
                placeholder={"请输出您的密码"}
                value={password}
                /*endContent={
                    <button className={"focus:outline-none"} type={"button"} onClick={toggleVisibility}>
                        {
                            isVisible ?
                                (<EyeSlashFilledIcon className="text-2xl text-default-400 pointer-events-none"/>)
                                :
                                (<EyeFilledIcon className="text-2xl text-default-400 pointer-events-none"/>)
                        }
                    </button>
                }*/
                type={"password"}
                isRequired={true}
                onChange={({target: {value}}) => setPassword(value)}
            />
            <Spacer y={5}/>
            <Button className={"font-serif"} fullWidth={true} color={"primary"} variant={"shadow"} onClick={() => {
                LoginService({username, password, setLoading}).then(r => {
                })
            }}>确 认 登 录</Button>
        </>
    );
}

/**
 * 手机号登录表单
 * @param loading
 * @param setLoading
 * @constructor
 */
function MobileLoginForm({loading, setLoading}: any) {
    /*手机号和验证码数据*/
    const [mobile, setMobile] = useState('');
    const [code, setCode] = useState('');
    /*倒计时*/
    const [countdown, setCountdown] = useState(0);
    
    /*获取消息（mobile）*/
    PubSub.unsubscribe('mobile')/*解触*/
    PubSub.subscribe('mobile', (_, data) => {
        setMobile(data)
        /*/接受完取消订阅*/
        PubSub.unsubscribe('mobile')
    })
    
    /*发送验证码*/
    const sendCode = () => {
        if (countdown > 0) return;
        
        if (!mobile || mobile.length !== 11) {
            ToastUtil("请输入正确的手机号", '🤨', "warning");
            return;
        }
        
        SendVerificationCode({mobile, type: 'LOGIN'}).then(success => {
            if (success) {
                setCountdown(60);
                const timer = setInterval(() => {
                    setCountdown(prevCountdown => {
                        if (prevCountdown <= 1) {
                            clearInterval(timer);
                            return 0;
                        }
                        return prevCountdown - 1;
                    });
                }, 1000);
            }
        });
    };
    
    return (
        <>
            <Input
                isClearable
                className={`dark:text-white`}
                id={'mobile'}
                name={'mobile'}
                type={"tel"}
                label={"手机号"}
                variant={"faded"}
                placeholder={"请输入您的手机号"}
                onClear={() => console.log("cleared")}
                isRequired={true}
                value={mobile}
                onChange={({target: {value}}) => setMobile(value)}
            />
            <Spacer y={1.5}/>
            <div className="flex w-full gap-2 items-end">
                <Input
                    className={`dark:text-white flex-1`}
                    id={'code'}
                    name={'code'}
                    type={"text"}
                    label={"验证码"}
                    variant={"faded"}
                    placeholder={"请输入验证码"}
                    isRequired={true}
                    value={code}
                    onChange={({target: {value}}) => setCode(value)}
                />
                <Button 
                    className="mb-[3px] min-w-[108px]" 
                    color="primary" 
                    variant="flat" 
                    onClick={sendCode}
                    isDisabled={countdown > 0}
                >
                    {countdown > 0 ? `重新发送(${countdown})` : "获取验证码"}
                </Button>
            </div>
            <Spacer y={5}/>
            <Button className={"font-serif"} fullWidth={true} color={"primary"} variant={"shadow"} onClick={() => {
                MobileLoginService({mobile, code, setLoading}).then(r => {
                })
            }}>确 认 登 录</Button>
        </>
    );
}

/**
 * 登录页
 * @constructor
 */
export default function Login() {
    /*路由*/
    const router = useRouter();
    /*Loading状态*/
    const [loading, setLoading] = useState(false);
    /*Tab选择*/
    const [selected, setSelected] = useState("password");

    /*UI组件*/
    return (
        <>
            <Tabs
                aria-label="登录选项"
                selectedKey={selected}
                onSelectionChange={setSelected as any}
                variant="underlined"
                color="primary"
                classNames={{
                    tabList: "gap-6 w-full relative rounded-none p-0 border-b border-divider",
                    cursor: "w-full bg-primary",
                    tab: "max-w-fit px-2 h-12",
                }}
            >
                <Tab key="password" title="账号密码登录">
                    <PasswordLoginForm loading={loading} setLoading={setLoading} />
                </Tab>
                <Tab key="mobile" title="手机号登录">
                    <MobileLoginForm loading={loading} setLoading={setLoading} />
                </Tab>
            </Tabs>
            <Spacer y={3}/>
            <div className={"flex justify-center"}>
                <CircularProgress className={!loading ? "hidden" : ""} size={"lg"} color="default"
                                  aria-label="加载中..."/>
            </div>
        </>
    )
}